<?php
namespace app\admin\controller;

use think\Controller;

/**
 * 后台登录
 * @author Kaisa
 * @version 2017-02-11
 */
class LoginController extends Controller {
    /**
     * 后台登录
     * @return mixed
     */
    public function index() {
    	// 已登录直接登录
    	if (session('admin_id')) {
            $this->redirect('admin/index/index');
        }
        return $this->fetch();
    }
	
    /**
     * 登录验证
     * @return string
     */
    public function login() {
        if(request()->isPost()){
            $data            = request()->only(['login_name', 'login_pwd', 'verify']);
            $validate_result = $this->validate($data, 'Login');
            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $where['login_name'] = $data['login_name'];
                $where['login_pwd'] = md5_salt($data['login_pwd']);
                $user = db('user')->where($where)->find();
                if (!empty($user)) {
                    if ($user['status'] != 1) {
                        $this->error('当前用户已禁用');
                    } else {
                        session('admin_id', $user['id']);
                        session('admin_name', $user['login_name']);
                        db('user')->update([
                        	'id'              => $user['id'],
                            'last_login_time' => date('Y-m-d H:i:s', time()),
                            'last_login_ip'   => $this->request->ip(),
                            'session_id'      => session_id()  //更改登录状态
                        ]);
                        $this->success('登录成功', 'index/index');
                    }
                } else {
                    $this->error('用户名或密码错误');
                }
            }
        }
    }

    /**
     * 退出登录
     */
    public function logout() {
        session('admin_id', null);
        session('admin_name', null);
        $this->success('退出成功', 'admin/login/index');
    }
}
